package huanzhao.erp.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import huanzhao.erp.domain.entity.GlobalSetting;
import huanzhao.erp.domain.entity.Position;
import huanzhao.erp.domain.entity.Task;
import huanzhao.erp.domain.enumerate.error.ValidationError;
import huanzhao.erp.domain.po.Result;
import huanzhao.erp.domain.types.AssignablePositionType;
import huanzhao.erp.domain.types.TeamPositionType;
import huanzhao.erp.domain.vo.PositionVO;
import huanzhao.erp.mapper.PositionMapper;
import huanzhao.erp.mapper.StaffMapper;
import huanzhao.erp.mapper.TeamMapper;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 提供职位管理和团队管理的服务
 *
 * @author April
 * 2024/10/2 13:35
 * @version 1.0
 */
@Service
public class PositionService extends ServiceImpl<PositionMapper, Position> {
    private final StaffMapper staffMapper;
    private final TeamMapper teamMapper;
    private final PositionMapper positionMapper;
    private final ConvertService convertService;
    private final BasicService basicService;

    public PositionService(StaffMapper staffMapper, TeamMapper teamMapper, PositionMapper positionMapper, ConvertService convertService, BasicService basicService) {
        this.staffMapper = staffMapper;
        this.teamMapper = teamMapper;
        this.positionMapper = positionMapper;
        this.convertService = convertService;
        this.basicService = basicService;
    }

    /**
     * 检查职位信息是否正确
     *
     * @param position 职位信息
     * @return Result<?>
     * 2024/6/18 上午11:38:27
     */
    public Result<?> checkPositionInfo(Position position) {
        if (position == null) {
            return Result.error(ValidationError.VALIDATION_ERROR, "职位信息为空");
        }
        if (position.getTeamId() == null || position.getTeamId() <= 0) {
            return Result.error(ValidationError.VALIDATION_ERROR, "团队id不合法");
        }
        if (position.getStaffId() == null || position.getStaffId() <= 0) {
            return Result.error(ValidationError.VALIDATION_ERROR, "员工id不合法");
        }

        if (position.getInput() == null) {
            return Result.error(ValidationError.VALIDATION_ERROR, "需指定是否为录入员");
        }
        if (position.getQc() == null) {
            return Result.error(ValidationError.VALIDATION_ERROR, "需指定是否为质检员");
        }
        if (position.getUp() == null) {
            return Result.error(ValidationError.VALIDATION_ERROR, "需指定是否为上架员");
        }

        if (staffMapper.getStaffBasicById(position.getStaffId()) == null) {
            return Result.error(ValidationError.VALIDATION_ERROR, "员工不存在");
        }
        if (teamMapper.getTeamById(position.getTeamId()) == null) {
            return Result.error(ValidationError.VALIDATION_ERROR, "渠道不存在");
        }
        return Result.ok("职位信息正确");
    }

    /**
     * 修改员工职位
     *
     * @param position 员工职位信息
     * @return Result<?>
     * 2024/6/18 上午11:45:04
     */
    public Result<?> updatePosition(Position position) {
        try {
            positionMapper.updateById(position);
            return Result.ok("修改成功");
        } catch (Exception e) {
            log.error("修改员工职位失败", e);
            return Result.error("其他原因出错，请联系开发人员");
        }
    }

    /**
     * 删除员工的归属团队关系
     *
     * @param staffId 员工id
     * @param teamId  团队id
     * @return Result<?>
     * 2024/6/18 下午3:23:53
     */
    public Result<?> removeStaffFromTeam(Long staffId, Long teamId) {
        try {
            positionMapper.removeStaffFromTeam(staffId, teamId);
            return Result.ok("移除成功");
        } catch (Exception e) {
            log.error("移除员工失败", e);
            return Result.error("其他原因出错，请联系开发人员");
        }
    }


    /**
     * 添加员工至团队
     *
     * @param position 员工职位信息
     * @return Result<?>
     * 2024/6/18 上午11:42:17
     */
    public Result<?> addStaffToTeam(Position position) {
        try {
            positionMapper.addStaffToTeam(position);
            return Result.ok("添加成功");
        } catch (Exception e) {
            log.error("添加员工至团队失败", e);
            return Result.error("其他原因出错，请联系开发人员");
        }
    }

    /**
     * 获取员工在团队中的职位
     *
     * @param staffId 员工id
     * @param teamId  团队id
     * @return Position
     * 2024/6/20 下午2:13:58
     */
    public PositionVO getStaffPosition(Long staffId, Long teamId) {
        return convertService.convertPosition(positionMapper.getStaffPosition(staffId, teamId));
    }

    /**
     * 获取当前员工的所有归属团队
     *
     * @param staffId 员工id
     * @return List<Team>
     * 2024/6/13 下午5:23:12
     */
    public List<PositionVO> getStaffPositions(Long staffId) {
        List<Position> positions = positionMapper.getStaffPositions(staffId);
        if (positions == null) {
            return Collections.emptyList();
        }
        List<PositionVO> result = new ArrayList<>();
        positions.forEach(position -> result.add(convertService.convertPosition(position)));
        return result;
    }

    /**
     * 获取当前员工所属团队id
     *
     * @return List<Long>
     * 2024/10/4 17:15:09
     */
    public List<Long> getStaffBelongTeamIds(Long staffId) {
        List<Long> ids = positionMapper.getStaffBelongTeamIds(staffId);
        if (ids == null) {
            return Collections.emptyList();
        }
        return ids;
    }

    /**
     * 判断员工是否具有指定团队的职位
     * 确保员工和团队都存在
     *
     * @param teamPositionType 团队中的职位：质检员、录入员、上架员
     * @return Result<?>
     * 2024/10/9 20:49:37
     */
    public Result<?> checkPosition(Long staffId, Long teamId, @NotNull TeamPositionType teamPositionType) {
        Position position = positionMapper.getStaffPosition(staffId, teamId);
        if (position == null) {
            return Result.error("员工不在该团队中");
        }
        switch (teamPositionType) {
            case QUALITY_CHECKER:
                if (!position.getQc()) {
                    return Result.error("员工不是质检员");
                }
                break;
            case ENTRY:
                if (!position.getInput()) {
                    return Result.error("员工不是录入员");
                }
                break;
            case PUBLISHER:
                if (!position.getUp()) {
                    return Result.error("员工不是上架员");
                }
                break;
        }
        return Result.ok("员工具有该职位");
    }

    /**
     * 根据任务获取员工的直属上级id
     *
     * @param task    任务详情
     * @return Long
     * 2024/10/10 10:36:53
     */
    public Long getSuperiorId(@NotNull Task task) {
        GlobalSetting globalSetting = basicService.getGlobalSetting();
        return switch (AssignablePositionType.of(task.getType())) {
            // 对于库管的任务，上级仓库负责人
            case WAREHOUSER -> globalSetting.getWarehouseHandlerId();
            // 对于采购的任务，上级采购负责人
            case PURCHASER -> globalSetting.getPurchaseHandlerId();
            // 对于维修组长的任务，上级为业务经理
            case REPAIR_LEADER -> globalSetting.getManagerId();
            // 对于维修员的任务，上级为维修组长
            case REPAIR -> globalSetting.getRepairLeaderId();
            // 对于渠道负责人的任务，上级为业务经理
            case TEAM_LEADER -> globalSetting.getManagerId();
            // 对于渠道中普通员工的任务，上级为渠道负责人，若渠道不存在则为业务经理
            case TEAM_STAFF -> {
                Long learId = teamMapper.getTeamLearId(task.getTeamId());
                if (learId == null) {
                    yield globalSetting.getManagerId();
                }
                yield learId;
            }
        };
    }
}
